// pages/message/message.js
const App = getApp();
const utils = require('../../utils/util.js')
var JIM = App.globalData.jim
Page({

  /**
   * 页面的初始数据
   */

  data: {
    getCateCountList:[{'title':'系统通知','unread':0,'type':1},{'title':'订单状态变更','unread':0,'type':2},{'title':'商品状态变更','unread':0,'type':3},{'title':'商品到期提醒','unread':0,'type':4},{'title':'钱包到账通知','unread':0,'type':5},{'title':'奖励与补偿','unread':0,'type':6}],
    isLogin:'',
    tabNum:0,
    delBtnWidth:120,
    data: [{ content: "1", right: 0 }],
    isScroll:true,
    windowHeight:0,
    markid:wx.getStorageSync('markId')
  },
 /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight
        });
      }
    });

    if(wx.getStorageSync('markId') != ''){
      if(JIM.isLogin()){
        //im登录完成调用
        that.getMsgList(); 
      }else{
        wx.showLoading({
          title: '登录中',
        })
        
        setTimeout(() => {
          that.getMsgList(); 
        }, 3000);
      }
    }
    
  },
  //获取会话列表(im操作)
  getMsgList:function (){
    let that = this;
    //获取会话列表
    JIM.getConversation().onSuccess(function(data) {
      wx.hideLoading();
      // console.log(data);
      let list = [];//新建数组
      var conversations = data.conversations;
      var newConversations = conversations.slice(-30);
      // console.log(newConversations)
      for (let i = 0; i < newConversations.length; i++) {
        list.unshift({avatar:'https://img1.odancool.com/defaultface001.jpg',avatarId:newConversations[i].avatar,name:newConversations[i].name,type:newConversations[i].type,unread_msg_count:newConversations[i].unread_msg_count,nickName:newConversations[i].nickName,mtime:utils.getTsFormatDate(newConversations[i].mtime),right:0});
      }
      //获取图像资源
      for (let j = 0;j < list.length;j++){
        utils.getResource(list[j].avatarId).then(function(successData) {
          list[j].avatar = successData
        })
      }
        
      
      // console.log(list);
      setTimeout(function(){
        that.setData({
          data:list
        })
       },300)
      
    })
    
    //断线监听
    JIM.onDisconnect(function(){
      App.IMInit()
    });
  },
  // drawStart: function (e) {
  //   // console.log("drawStart");  
  //   var touch = e.touches[0]

  //   for(var index in this.data.data) {
  //     var item = this.data.data[index]
  //     item.right = 0
  //   }
  //   this.setData({
  //     data: this.data.data,
  //     startX: touch.clientX,
  //   })

  // },
  // drawMove: function (e) {
  //   var touch = e.touches[0]
  //   var item = this.data.data[e.currentTarget.dataset.index]
  //   var disX = this.data.startX - touch.clientX
    
  //   if (disX >= 20) {
  //     if (disX > this.data.delBtnWidth) {
  //       disX = this.data.delBtnWidth
  //     }
  //     item.right = disX
  //     this.setData({
  //       isScroll: false,
  //       data: this.data.data
  //     })
  //   } else {
  //     item.right = 0
  //     this.setData({
  //       isScroll: true,
  //       data: this.data.data
  //     })
  //   }
  // },  
  // drawEnd: function (e) {
  //   var item = this.data.data[e.currentTarget.dataset.index]
  //   if (item.right >= this.data.delBtnWidth/2) {
  //     item.right = this.data.delBtnWidth
  //     this.setData({
  //       isScroll: true,
  //       data: this.data.data,
  //     })
  //   } else {
  //     item.right = 0
  //     this.setData({
  //       isScroll: true,
  //       data: this.data.data,
  //     })
  //   }
  // },
  //去往聊天界面
  goToChat:function (e) {
    var name = e.currentTarget.dataset.name;
    // 重置单聊会话，调用则成功，无回调函数
    // var name = this.data.name;
    JIM.resetUnreadCount({
      'username' : name
    });

    let receiveList = this.data.data;

    for(var i = 0;i < receiveList.length;i++){
      if (receiveList[i].name == name){
        receiveList[i].unread_msg_count = 0;
      }
    }
    // console.log(receiveList)
    this.setData({
      data:receiveList
    })


    wx.navigateTo({
      url: '/pages/message/chat/chat?name='+name,
    })
  },
  // 会话与通知切换
  btnTab:function () {
    var tabNum = this.data.tabNum;
    if(tabNum == 0){
      tabNum = 1
    }else if(tabNum == 1){
      tabNum = 0
    }
    this.setData({
      tabNum:tabNum
    })
  },
  //获取消息通知分类
  getCateCount:function () {
    var getCateCountList = this.data.getCateCountList;
    utils.requestUrl({
      url:'/niu/apiv3/noti_getcatecount.php',
      params: {
        markid:wx.getStorageSync('markId')
      }
    }).then((res) =>{
      console.log(res.data);
      for (var i = 0;i < res.data.data.length;i++){
        if(res.data.data[i].type == 0){
          getCateCountList[0].unread = res.data.data[i].unread
        }else if(res.data.data[i].type == 1){
          getCateCountList[1].unread = res.data.data[i].unread
        }else if(res.data.data[i].type == 2){
          getCateCountList[2].unread = res.data.data[i].unread
        }else if(res.data.data[i].type == 3){
          getCateCountList[3].unread = res.data.data[i].unread
        }else if(res.data.data[i].type == 4){
          getCateCountList[4].unread = res.data.data[i].unread
        }else if(res.data.data[i].type == 5){
          getCateCountList[5].unread = res.data.data[i].unread
        }
      }

      this.setData({
        getCateCountList:getCateCountList
      })
    })
  },
  goToDetail:function (e) {
    var typeid = e.currentTarget.dataset.type;
    var title = e.currentTarget.dataset.title;
    var list = this.data.getCateCountList;
    list[typeid].unread = 0;
    this.setData({
      getCateCountList:list
    })
    wx.navigateTo({
      url: '/pages/message/messagesDetail/messagesDetail?typeid='+typeid+'&title='+title,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getCateCount();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var isLogin = this.data.isLogin;
    if(wx.getStorageSync('markId') != ''){
      this.setData({
        markid:wx.getStorageSync('markId')
      })

      if(isLogin){
        wx.showLoading({
          title: '登录中'
        })
        if(JIM.isLogin()){
          //im登录完成调用
          that.getMsgList(); 
        }else{
         
          App.IMInit()
          setTimeout(() => {
            that.getMsgList(); 
          }, 3000);
        }
      }

      //消息实时监听
      JIM.onMsgReceive(function(data) {
        // console.log(data);
        var receiveList = that.data.data;
        var name = data.messages[0].from_username;
        var newArr;
        for (var i = 0;i < receiveList.length;i++){
          if (receiveList[i].name == name){
            var unread_msg_count =  receiveList[i].unread_msg_count++
            newArr = {avatar:receiveList[i].avatar,avatarId:receiveList[i].avatar,name:receiveList[i].name,type:receiveList[i].type,unread_msg_count:unread_msg_count+1,nickName:receiveList[i].nickName,mtime:utils.getTsFormatDate(receiveList[i].mtime),right:0}
            receiveList.splice(i,1);
          }
        }
        receiveList.unshift(newArr)
        that.setData({
          data:receiveList
        })
        var msg = wx.getStorageSync(data.messages[0].from_username);
        msg.push(data.messages[0])
        wx.setStorageSync(data.messages[0].from_username, msg)
      });
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if(wx.getStorageSync('markId') == ''){
      this.setData({
        isLogin:true
      })
    }else{
      this.setData({
        isLogin:false
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})